const fs = require('fs');
const path = require('path');
const express = require('express');
const filePath = path.resolve(__dirname, './json/outlay.json');
const dateService = require('./utils/date');
const { apiPre } = require('./config');
const { getInfoByKey, getListMaxId, listSortByKey } = require('./utils/tool');

module.exports = (app, server, compiler) => {
  const modulePre = `${apiPre}/outlay`;
  app.use(express.json());
  app.use(express.urlencoded());

  // 对当前模块列表数据进行默认排序设置
  const cpListSort = list => {
    return listSortByKey({ list, key: 'createDate', isDesc: true, type: 'time' });
  }
  // 列表
  app.get(`${modulePre}/list`, (req, res) => {
    fs.readFile(filePath, 'utf-8', async (err, result) => {
      if (err) {
        res.status(503).send('数据读取错误');
        return false;
      }
      await new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve('123')
        }, 1000);
      })
      const data = !result ? [] : JSON.parse(result);
      res.json({
        code: 200,
        data: cpListSort(data.filter(item => item.isDel === 0)),
      })
    })
  })
  // 新增
  app.post(`${modulePre}/save`, (req, res) => {
    const params = req.body;
    if (!params.name) {
      res.json({ code: 500, data: null, msg: 'name is missing' });
      return;
    }
    if (!params.money) {
      res.json({ code: 500, data: null, msg: 'money is missing' });
      return;
    }
    if (!params.type) {
      res.json({ code: 500, data: null, msg: 'type is missing' });
      return;
    }
    fs.readFile(filePath, 'utf-8', (err, result) => {
      if (err) {
        res.err('数据读取错误');
        return false;
      }
      const dataList = !result ? [] : JSON.parse(result);
      const aData = {
        id: `${getListMaxId(dataList) + 1}`,
        name: params.name,
        money: parseInt(params.money),
        type: params.type,
        time: params.time,
        mark: params.mark || '',
        createDate: dateService.getCpDate(),
        isDel: 0,
      };
      const newDataList = [].concat(dataList, aData);
      fs.writeFile(filePath, JSON.stringify(cpListSort(newDataList)), 'utf-8', (err, result2) => {
        if (err) {
          res.err('数据存储错误');
          return false;
        }
        res.json({
          code: 200,
          data: aData,
        });
      });
    })
  })
  // 更新
  app.post(`${modulePre}/update`, (req, res) => {
    const params = req.body;
    if (!params) {
      res.json({ code: 500, data: null, msg: '缺少参数' });
      return;
    }
    if (!params.id) {
      res.json({ code: 500, data: null, msg: '缺少id字段' });
      return;
    }
    fs.readFile(filePath, 'utf-8', (err, result) => {
      if (err) {
        res.err('数据读取错误');
        return false;
      }
      let dataList = !result ? [] : JSON.parse(result);
      dataList = dataList.map(item => {
        if (item.id === params.id) {
          return {
            ...item,
            name: params.name,
            money: parseInt(params.money),
            type: params.type,
            time: params.time,
            mark: params.mark,
          }
        } else {
          return item;
        }
      })
      fs.writeFile(filePath, JSON.stringify(dataList), 'utf-8', (err, result2) => {
        if (err) {
          res.err('数据存储错误');
          return false;
        }
        res.json({
          code: 200,
          data: params,
        });
      });
    })
  })
  // 删除
  app.post(`${modulePre}/delete`, (req, res) => {
    const params = req.body;
    if (!params.id) {
      res.json({ code: 500, data: null, msg: '缺少id字段' });
      return;
    }
    fs.readFile(filePath, 'utf-8', (err, result) => {
      if (err) {
        res.err('数据读取错误');
        return false;
      }
      const aNum = Math.random();
      if (aNum < 0.3) {
        res.status(400).send('Bad Request')
        return;
      }
      let dataList = !result ? [] : JSON.parse(result);
      dataList = dataList.map(item => {
        if (item.id === params.id) {
          item.isDel = 1;
        }
        return item;
      })
      fs.writeFile(filePath, JSON.stringify(dataList), 'utf-8', (err, result2) => {
        if (err) {
          res.err('数据存储错误');
          return false;
        }
        res.json({
          code: 200,
          data: params,
        });
      });
    })
  })

  // 详情
  app.get(`${modulePre}/:id`, (req, res) => {
    const params = req.params;
    if (!params.id) {
      res.json({ code: 500, data: null, msg: '缺少id字段' });
      return;
    }
    fs.readFile(filePath, 'utf-8', (err, result) => {
      if (err) {
        res.err('数据读取错误');
        return false;
      }
      const dataList = !result ? [] : JSON.parse(result);

      res.json({
        code: 200,
        data: getInfoByKey(dataList, params.id),
      });
    })
  })
}